package com.geek.gkmember.framework.trace.interceptor;

import com.geek.gkmember.framework.trace.TraceContext;
import com.geek.gkmember.framework.trace.util.TraceIdGeneratorUtils;
import com.geek.gkmember.framework.trace.model.TraceInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h1>全局ID初始化赋值拦截处理。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2022-02-19
 *
 */
public class TraceInterceptor extends HandlerInterceptorAdapter {

    private static final String NAME = TraceInterceptor.class.getSimpleName();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String traceId = request.getParameter(TraceInfo.TRACE_ID_NAME);
        if (StringUtils.isBlank(traceId)) {
            traceId = request.getHeader(TraceInfo.TRACE_ID_NAME);
        }
        TraceContext.setCurrentSpan(TraceInfo.create(TraceIdGeneratorUtils.getTraceId(traceId)).setMarker(NAME));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        TraceContext.removeCurrentTrace(NAME);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TraceContext.removeCurrentTrace(NAME);
    }
}